package com.wang.jmonkey.ca.handler.code;

import com.wang.jmonkey.ca.model.ValidateCode;
import com.wang.jmonkey.common.constant.ValidateConstant;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Description 创建验证码模板类
 * @Author HeJiawang
 * @Date 2021/5/11 9:09
 */
public abstract class AbstractValidateCodeHandler implements ValidateCodeHandler, ApplicationContextAware {

    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    /**
     * 模板方法
     * @param validateCodeType
     * @param request
     * @param response
     * @return
     */
    @Override
    public ValidateCode build(ValidateConstant.ValidateCodeType validateCodeType,
                              HttpServletRequest request, HttpServletResponse response) {

        Map<String, ValidateCodeGenerator> generatorMap = context.getBeansOfType(ValidateCodeGenerator.class);
        ValidateCode validateCode = generatorMap.get(validateCodeType.getKey() + "Generator").generate();

        save(validateCode);
        send(validateCode, response);

        return validateCode;
    }
}
